package com.example.service;

import com.example.entity.ClubApplication;
import com.example.mapper.ClubApplicationMapper;
import com.example.mapper.ClubMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;

@Service
public class ClubApplicationService {
    @Resource
    private ClubApplicationMapper clubApplicationMapper;
    
    @Resource
    private ClubMapper clubMapper;

    public PageInfo<ClubApplication> getApplicationsByClubId(Integer clubId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClubApplication> list = clubApplicationMapper.selectByClubId(clubId);
        return new PageInfo<>(list);
    }

    public PageInfo<ClubApplication> getAllApplications(Integer pageNum, Integer pageSize) {
        System.out.println("=== 开始查询所有社团申请 ===");
        System.out.println("分页参数: pageNum=" + pageNum + ", pageSize=" + pageSize);
        
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<ClubApplication> list = clubApplicationMapper.selectAll();
            
            System.out.println("查询结果: 共" + list.size() + "条记录");
            if (list.size() > 0) {
                System.out.println("第一条记录: " + list.get(0));
            }
            
            System.out.println("=== 查询完成 ===");
            return new PageInfo<>(list);
        } catch (Exception e) {
            System.out.println("查询过程中发生错误: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @Transactional
    public void approveApplication(Integer applicationId) {
        // 获取申请信息
        ClubApplication application = clubApplicationMapper.selectById(applicationId);
        if (application == null) {
            throw new RuntimeException("申请不存在");
        }
        
        // 更新申请状态
        clubApplicationMapper.updateStatus(applicationId, "已通过");
        // 添加成员记录
        clubMapper.addMember(application.getClubId(), application.getStudentId());


    }

    @Transactional
    public void rejectApplication(Integer applicationId) {
        // 获取申请信息
        ClubApplication application = clubApplicationMapper.selectById(applicationId);
        if (application == null) {
            throw new RuntimeException("申请不存在");
        }
        
        // 更新申请状态
        clubApplicationMapper.updateStatus(applicationId, "已拒绝");
    }

    public List<ClubApplication> getByClubId(Integer clubId) {
        return clubApplicationMapper.getByCludId(clubId);
    }

    public PageInfo<ClubApplication> getByCondition(ClubApplication param, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClubApplication> list = clubApplicationMapper.getByCondition(param);
        return new PageInfo<>(list);
    }
}